package priv.yiyuan.example.design.proxy;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

/**
 * 加密解密装饰器
 *
 * @author YiYuan
 * @data 2025/9/25
 * @apoNote
 */
public class EncryptionDecorator extends FileOperationDecorator {

    public EncryptionDecorator(FileOperation decoratedFileOperation) {
        super(decoratedFileOperation);
    }

    private String encrypt(String data) {
        System.out.println("[加密装饰器] 正在加密数据...");
        return Base64.getEncoder().encodeToString(data.getBytes(StandardCharsets.UTF_8));
    }

    private String decrypt(String encryptedData) {
        System.out.println("[加密装饰器] 正在解密数据...");
        return new String(Base64.getDecoder().decode(encryptedData), StandardCharsets.UTF_8);
    }

    @Override
    public void write(String filePath, String content) {
        String encryptedContent = this.encrypt(content);
        System.out.println("[加密装饰器] 加入加密后的内容。");
        decoratedFileOperation.write(filePath, encryptedContent);
    }

    @Override
    public String read(String filePath) {
        String encryptedContent = decoratedFileOperation.read(filePath);
        if (encryptedContent != null && !encryptedContent.isEmpty()) {
            System.out.println("[加密装饰器] 读取到加密内容, 正在解密。");
            return decrypt(encryptedContent);
        }

        return "";
    }
}
